package com.cloud.pikachu.dingtalk.service.credential;

import com.cloud.pikachu.dingtalk.aes.DingTalkEncryptException;
import com.cloud.pikachu.dingtalk.aes.DingTalkJsApiSingnature;
import com.cloud.pikachu.dingtalk.constant.DingtalkConstant;
import com.cloud.pikachu.dingtalk.service.token.JsApiTickenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 网页签名计算Service
 * @author ABug
 */
@Service
public class ViewCredentialService {
    private static final Logger logger = LoggerFactory.getLogger(ViewCredentialService.class);
    @Autowired
    private JsApiTickenService jsApiTickenService;

    /**
     * 计算网页签名
     * @param viewUrl
     * @param agentId
     * @return
     */
    public ViewCredentialModel getViewCredential(String viewUrl , String agentId){
        ViewCredentialModel returnData = new ViewCredentialModel();
        try{
            viewUrl = viewUrl.replace("@@@@" , "&");

            returnData.setUrl(viewUrl);
            returnData.setCorpId(DingtalkConstant.corpid);
            returnData.setAgentId(agentId);
            returnData.setNonce(DingtalkConstant.nonce);
            returnData.setTimeStamp(System.currentTimeMillis() / 1000);
            returnData.setTikcet(jsApiTickenService.getJsApiTicken());
            String jsApiSingnature = DingTalkJsApiSingnature.getJsApiSingnature(viewUrl, DingtalkConstant.nonce, returnData.getTimeStamp(), returnData.getTikcet());
            returnData.setTikcet(jsApiSingnature);

            returnData.setCode(200);
            returnData.setMsg("OK");
        } catch (DingTalkEncryptException e) {
            returnData = new ViewCredentialModel();
            returnData.setCode(500);
            returnData.setMsg(e.getMessage());
            logger.error("网页签名失败 : 网页地址信息["+viewUrl+"]");
        }
        return returnData;
    }
}
